/*
 * (C) Copyright 2024 赤い月 All Rights Reserved.
 * Description：
 * Author：赤い月
 * Date: 2024/2/13
 * Modify Record:
 */
#pragma once

#include <QNetworkAccessManager>
#include <QNetworkCookie>
#include <QNetworkCookieJar>
#include <QNetworkReply>

class HttpUtils : public QObject {
  Q_OBJECT

 public:
  explicit HttpUtils(QObject* parent = nullptr);
  Q_INVOKABLE void logIn(const QString& username, const QString& password);
  Q_INVOKABLE void sendRequest(const QString& url,
                               const QByteArray& data = QByteArray(),
                               const bool isPost = false);
  Q_INVOKABLE void getImage(const QString& url);
  Q_INVOKABLE void getMusic(const QString& url);

 signals:
  void ReplySignal(QByteArray);
  void ImageDownloaded(QPixmap);
  void MusicDownloaded(QByteArray);

 private slots:
  void reply_finished(QNetworkReply* reply);

 private:
  QString BASE_URL;
  std::shared_ptr<QNetworkAccessManager> manager_;
  bool store_cookie_;
  QList<QNetworkCookie> stored_cookies_;

  QNetworkReply* reply;

  void configureSsl(QNetworkRequest& request);
  void setNetworkRequestHeader(QNetworkRequest& request);
  void handleCookies(QNetworkReply* reply);
  QByteArray readReply(QNetworkReply* reply);
};
